class_name EnemyManager
extends Node

signal round_changed(round_number: int)
signal round_completed
signal game_completed

#初始关卡时间
const ROUND_BASE_TIME: int = 10
#每通过一关，延长的关卡时间
const ROUND_GROWTH: int = 5
#初始敌人的生成频率
const BASE_ENEMY_SPAWN_TIME: float = 4.0
#随着关卡提升，敌人生成频率的提升
const ENEMY_SPAWN_TIME_GROWTH: float = -.2
#最大关卡数
const MAX_ROUNDS: int = 18

@export_group("BOSS")
#敌人boss
#近战
#白无常
@export var enemy_boss_close_scene: PackedScene

#黑无常
@export var 黑无常_scene: PackedScene

#牛头
@export var 牛头_scene: PackedScene

#牛头
@export var 马面_scene: PackedScene

#牛魔王
@export var 牛魔王_scene: PackedScene


#冲击boss
#阎王爷
@export var enemy_boss_rash_scene: PackedScene


#远程boss
#无天
@export var enemy_boss_range_scene: PackedScene
@export var 魔观音_scene: PackedScene
@export var 御剑天师_scene: PackedScene
@export var 鬼卒_scene: PackedScene




@export_group("小兵")
#敌人小兵
#白衣女鬼
@export var enemy_scene: PackedScene
#攻击鬼兵
@export var enemy_range_scene: PackedScene
#剑鬼兵
@export var enemy_close_scene: PackedScene
#剑盾鬼兵
@export var enemy_shield_scene: PackedScene



@export_group("其他")
#敌人生成挂载节点
@export var enemy_spawn_root: Node
#敌人生成的区间范围，这里是四个边
@export var spawn_rect1: ReferenceRect
@export var spawn_rect2: ReferenceRect
@export var spawn_rect3: ReferenceRect
@export var spawn_rect4: ReferenceRect

#升级管理器
@export var upgrade_manager: UpgradeManager

@onready var spawn_interval_timer: Timer = $SpawnIntervalTimer
@onready var round_timer: Timer = $RoundTimer

#每个关卡生成哪些敌人的字典
var round_boss_dictionary: Dictionary[int, Array] = {}
var round_enemy_dictionary: Dictionary[int, Array] = {}




var _round_count: int
var round_count: int:
	get:
		return _round_count
	set(value):
		_round_count = value
		round_changed.emit(_round_count)
		spawned_boss = true
		
var spawned_enemies: int

#是否生了成关卡boss
var spawned_boss: = true

func _ready():
	spawn_interval_timer.timeout\
		.connect(_on_spawn_interval_timer_timeout)
	round_timer.timeout.connect(_on_round_timer_timeout)
	GameEvents.enemy_died.connect(_on_enemy_died)
	upgrade_manager.upgrades_completed.connect(_on_upgrades_completed)
	
	#初始化关卡boss信息
	round_boss_dictionary.set(1,[enemy_boss_close_scene])
	#round_boss_dictionary.set(1,[enemy_boss_range_scene])
	round_boss_dictionary.set(2,[黑无常_scene])
	round_boss_dictionary.set(3,[enemy_boss_close_scene,黑无常_scene])
	round_boss_dictionary.set(4,[牛头_scene])
	round_boss_dictionary.set(5,[马面_scene])
	round_boss_dictionary.set(6,[牛头_scene,马面_scene])
	round_boss_dictionary.set(7,[鬼卒_scene])
	round_boss_dictionary.set(8,[牛头_scene,马面_scene,鬼卒_scene])
	round_boss_dictionary.set(9,[enemy_boss_close_scene,黑无常_scene,牛头_scene,马面_scene,鬼卒_scene])
	round_boss_dictionary.set(10,[enemy_boss_rash_scene])
	round_boss_dictionary.set(11,[enemy_boss_close_scene,黑无常_scene,牛头_scene,马面_scene,鬼卒_scene,enemy_boss_rash_scene])
	round_boss_dictionary.set(12,[魔观音_scene])
	round_boss_dictionary.set(13,[御剑天师_scene])
	round_boss_dictionary.set(14,[魔观音_scene,御剑天师_scene])
	round_boss_dictionary.set(15,[enemy_boss_close_scene,黑无常_scene,牛头_scene,马面_scene,鬼卒_scene,enemy_boss_rash_scene,魔观音_scene,御剑天师_scene])
	round_boss_dictionary.set(16,[enemy_boss_range_scene])
	round_boss_dictionary.set(17,[enemy_boss_range_scene,魔观音_scene])
	round_boss_dictionary.set(18,[enemy_boss_close_scene,黑无常_scene,牛头_scene,马面_scene,鬼卒_scene,enemy_boss_rash_scene,魔观音_scene,御剑天师_scene,enemy_boss_rash_scene])
	
	
	#初始化关卡小兵信息
	round_enemy_dictionary.set(1,[enemy_scene])
	#round_enemy_dictionary.set(1,[enemy_scene,enemy_shield_scene,enemy_range_scene])
	round_enemy_dictionary.set(2,[enemy_scene])
	round_enemy_dictionary.set(3,[enemy_scene])
	round_enemy_dictionary.set(4,[enemy_scene])
	round_enemy_dictionary.set(5,[enemy_scene,enemy_shield_scene])
	round_enemy_dictionary.set(6,[enemy_scene,enemy_shield_scene])
	round_enemy_dictionary.set(7,[enemy_scene,enemy_shield_scene])
	round_enemy_dictionary.set(8,[enemy_scene,enemy_shield_scene])
	round_enemy_dictionary.set(9,[enemy_scene,enemy_shield_scene])
	round_enemy_dictionary.set(10,[enemy_scene,enemy_shield_scene,enemy_range_scene])
	round_enemy_dictionary.set(11,[enemy_scene,enemy_shield_scene,enemy_range_scene])
	round_enemy_dictionary.set(12,[enemy_scene,enemy_shield_scene,enemy_range_scene])
	round_enemy_dictionary.set(13,[enemy_scene,enemy_shield_scene,enemy_range_scene])
	round_enemy_dictionary.set(14,[enemy_scene,enemy_shield_scene,enemy_range_scene])
	round_enemy_dictionary.set(15,[enemy_scene,enemy_shield_scene,enemy_range_scene])
	round_enemy_dictionary.set(16,[enemy_scene,enemy_shield_scene,enemy_range_scene])
	round_enemy_dictionary.set(17,[enemy_scene,enemy_shield_scene,enemy_range_scene])
	round_enemy_dictionary.set(18,[enemy_scene,enemy_shield_scene,enemy_range_scene])
	
	
	
	
	

func start():
	if is_multiplayer_authority():
		begin_round()


func synchronize(to_peer_id: int = -1):

	if !is_multiplayer_authority():
		return
	
	var data = {
		"round_timer_is_running": !round_timer.is_stopped(),
		"round_timer_time_left": round_timer.time_left,
		"round_count": round_count
	}
	
	if to_peer_id > -1 && to_peer_id != 1:
		_synchronize.rpc_id(to_peer_id, data)
	else:
		_synchronize.rpc(data)

@rpc("authority", "call_remote", "reliable")
func _synchronize(data: Dictionary):
	var wait_time = data["round_timer_time_left"]
	if wait_time >0:
		round_timer.wait_time = data["round_timer_time_left"]
	if data["round_timer_is_running"]:
		round_timer.start()
	round_count = data["round_count"]

func get_round_time_remaining() -> float:
	return round_timer.time_left

func begin_round():
	

	
	
	round_count += 1
	round_timer.wait_time = ROUND_BASE_TIME + ((round_count - 1) * ROUND_GROWTH )
	round_timer.start()
	
	_on_spawn_interval_timer_timeout()
	
	var diff = MultiplayerConfig.diff_type
	var round = 0.0
	var growth = 0.0
	if diff == "一般":
		round = -1.0
		growth = -0.1
	elif diff == "困难":
		round = -2.0
		growth = -0.2
	
	spawn_interval_timer.wait_time = clamp((BASE_ENEMY_SPAWN_TIME + round) +\
		((round_count - 1) * (ENEMY_SPAWN_TIME_GROWTH + growth)),0.5,BASE_ENEMY_SPAWN_TIME)

	spawn_interval_timer.start()
	synchronize()


func check_round_completed():
	if !round_timer.is_stopped():
		return
	
	
	if spawned_enemies <= 0:
		var groups = enemy_spawn_root.get_children()
		
		for group in groups:
			print(group)
		
		if round_count == MAX_ROUNDS:
			complete_game()
		else:
			round_completed.emit()
	
func complete_game():
	await get_tree().create_timer(2).timeout
	game_completed.emit()
	

func get_random_spawn_position() -> Vector2:
	var asa = randi_range(1,4)
	var spawn_rect := spawn_rect1
	if asa == 2:
		spawn_rect = spawn_rect2
	if asa == 3:
		spawn_rect = spawn_rect2
	if asa == 4:
		spawn_rect = spawn_rect4
		
	var x = randf_range(0, spawn_rect.size.x)
	var y = randf_range(0, spawn_rect.size.y)
	
	return spawn_rect.global_position + Vector2(x, y)


func spawn_enemy():

	var asb = round_enemy_dictionary.get(round_count)
	for item in asb:
		var enemy_range = item.instantiate() as Node2D
		enemy_range.global_position = get_random_spawn_position()
		enemy_range.add_to_group("enemy")
		enemy_spawn_root.add_child(enemy_range, true)
		spawned_enemies += 1

	
	if spawned_boss:
		
		var asa = round_boss_dictionary.get(round_count)
		
		for item in asa:
			var boss = item.instantiate() as Node2D
			boss.global_position = get_random_spawn_position()
			boss.add_to_group("enemy")
			enemy_spawn_root.add_child(boss, true)
			boss.health_component.reset_health(boss.health_component.max_health + round_count*4.0)
			spawned_enemies += 1
		
		spawned_boss = false
		
		
		
	
	



func _on_spawn_interval_timer_timeout():
	if is_multiplayer_authority():
		spawn_enemy()
		spawn_interval_timer.start()

func _on_round_timer_timeout():
	if is_multiplayer_authority():
		spawn_interval_timer.stop()
		check_round_completed()


func _on_enemy_died():
	spawned_enemies -= 1
	check_round_completed()

func _on_upgrades_completed():
	begin_round()
